import {
  isSingleChoice,
  isMultiChoice,
  isJudge,
  isLink,
  isFillIn,
  isSort
} from '@ebag/rb-question-vue3'
import { cloneDeep } from 'lodash'
import katex from 'katex'
import { formatHtml } from '@/utils/formula'

/**
 * tip:  答案回显先根据作答方式显示 再根据题型显示
 */
export const rbqOption = {
  host: {
    resourceHost: 'https://contres.readboy.com/' // 静态资源(图片、音频等)服务器域名
  },
  displayAnswer: false, // 是否显示题目答案，显示答案时不能作答
  interactive: false, // 是否可作答
  readonly: true, // 可作答时是否只读（只显示之前的作答情况但不能改）
  // answerColor?: string; // 答案颜色，值为css颜色声明
  // enableContentFold?: boolean; // 是否启用题干折叠，默认不启用
  // enableSolution?: boolean; // 是否显示答案和解析，默认不显示
  fontSize: '0.08333rem'
}

/**
 * 返回标准题目结构
 * @param {} param {id, correct_answer, sub_topic_info ...}
 * @returns
 */
export const getParseData = param => {
  const question = cloneDeep(param)
  return {
    data: question,
    typeDetail: question.type
  }
}

/**
 * 处理连线题数据
 * @param {Array} answer
 * @returns
 */
function drawCorrectLinkAnswer(answer) {
  const optionPairs = []
  for (let i = 0; i !== answer.length; i++) {
    for (let n = 0; n !== answer[i].length; n++) {
      optionPairs.push([
        [i, n],
        [i + 1, answer[i][n]]
      ])
    }
  }
  return optionPairs
}

const removeP = str => str.replace('<p>', '').replace('</p>', '')
export function handleAnswer(answer, question, imgUrlArr) {
  let result = ''
  if (question.data.answer_method === 3) {
    result = answer.join(' ')
  } else if (
    isSingleChoice(question, rbqOption) ||
    isMultiChoice(question, rbqOption)
  ) {
    result = answer.map(v => String.fromCharCode(65 + v)).join('')
  }
  if (isJudge(question, rbqOption)) {
    if (question.data.subject === 3) {
      result = answer[0] === 'T' ? '正确' : '错误'
    } else {
      result = answer[0] === 0 ? '正确' : '错误'
    }
  }
  if (isFillIn(question, rbqOption)) {
    result = answer.join('; ')
  }
  if (isSort(question, rbqOption)) {
    result = answer.map(v => v + 1).join('; ')
  }
  if (isLink(question, rbqOption)) {
    result = question.data.accessory
      .map(item => removeP(item.options[0]) + '——' + removeP(item.options[1]))
      .join('<br>')
  }
  if (imgUrlArr?.length) {
    let list = ''
    imgUrlArr.forEach(url => {
      list += `</br><img src='${url}' />`
    })
    result += list
  }
  return result
}

/**
 * 规范获取安卓的作答数据
 * 安卓传递过来的答案统一为[]string格式，所以答案回显时需要进行处理
 */
// 第三个参数是图片列表
export function getNormalizeData(userAnswer, questionData, imgUrlArr) {
  let result = userAnswer
  // 根据作答类型判断
  if (questionData.data.answer_method === 3) {
    result = userAnswer
  }
  // 单选题、判断题
  else if (
    isSingleChoice(questionData, rbqOption) ||
    isJudge(questionData, rbqOption)
  ) {
    result = [Number(userAnswer[0])]
  } else if (
    // 多选题、排序题
    (isMultiChoice(questionData, rbqOption) ||
      isSort(questionData, rbqOption)) &&
    Array.isArray(userAnswer)
  ) {
    result = userAnswer.map(v => Number(v))
  } else if (isLink(questionData, rbqOption)) {
    // 连线题
    const newArr = []
    console.log('连线题', userAnswer)
    userAnswer.sort((a, b) => a.split(',')[0] - b.split(',')[0])
    userAnswer.forEach(v => {
      const arr = v.split(',')
      newArr.push(Number(arr[1]))
    })
    result = drawCorrectLinkAnswer([newArr])
  }
  if (imgUrlArr) {
    imgUrlArr = JSON.parse(imgUrlArr)
  }
  return format(handleAnswer(result, questionData, imgUrlArr))
}

// 格式化答案
const format = str => {
  // 答案由$$包围
  if (str.match(/^[$]/i) && str.match(/[$]$/i)) {
    return katex.renderToString(str.slice(1, str.length - 1).toString(), {
      throwOnError: false
    })
  } else if (str.match(/[<tex]/i)) {
    return formatHtml(str)
  }
  return str
}
